package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.AIService;
import com.xuanzheng.company.service.impl.AIServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 更新AI设置Servlet
 */
@WebServlet("/updateAISetting")
public class UpdateAISettingServlet extends HttpServlet {
    
    private final AIService aiService = new AIServiceImpl();
    private final Gson gson = new Gson();
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查是否为管理员
            if (!isAdmin(request)) {
                result.put("success", false);
                result.put("message", "权限不足");
                out.print(gson.toJson(result));
                return;
            }
            
            // 读取请求体
            StringBuilder jsonBuilder = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonBuilder.append(line);
            }
            
            // 解析JSON
            JsonObject requestJson = JsonParser.parseString(jsonBuilder.toString()).getAsJsonObject();
            String key = requestJson.get("key").getAsString();
            String value = requestJson.get("value").getAsString();
            
            if (key == null || key.trim().isEmpty() || value == null) {
                result.put("success", false);
                result.put("message", "参数不能为空");
                out.print(gson.toJson(result));
                return;
            }
            
            // 更新设置
            boolean success = aiService.updateSystemSetting(key, value);
            
            if (success) {
                result.put("success", true);
                result.put("message", "设置更新成功");
            } else {
                result.put("success", false);
                result.put("message", "设置更新失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "服务器内部错误");
        }
        
        // 修改这一行：使用gson.toJson()替代objectMapper.writeValueAsString()
        out.print(gson.toJson(result));
        out.flush();
        out.close();
    }
    
    private boolean isAdmin(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) return false;
        
        User user = (User) session.getAttribute("user");
        return user != null && user.getRole() == 2; // 系统管理员
    }
}
